package com.igeek.boot.controller;

import com.github.pagehelper.PageInfo;
import com.igeek.boot.entity.User;
import com.igeek.boot.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * *User 訫
 * *Description TODO
 * *Date 2024/8/20
 **/
@RestController
public class UserController {
    @Autowired
    UserServiceImpl userService;

    //post方式：添加用户  （name age gender pwd birthday）
    @PostMapping("/addUser")
    public int addUser(@RequestBody User user){
        return userService.addUser(user);
    }

    //put方式：  根据id 更新用户头像 （pic）  并且实现文件上传
    @PutMapping("/updateUser")
    public int updateUser(
            Integer id,
            @RequestPart("pic") MultipartFile pic) throws IOException {
        //文件上传
        int row = 0;
        if(!pic.isEmpty()) {
            String oldFilename = pic.getOriginalFilename();
            String newFilename = UUID.randomUUID().toString() + oldFilename.substring(oldFilename.indexOf("."));
            String newPath = "D:\\极客营133\\spring_boot\\1.SpringBoot\\pic\\";
            row = userService.updateUser(id, newPath + newFilename);
            if (row > 0) {
                pic.transferTo(new File(newPath, newFilename));
            }
        }
        return row;
    }

    //delete方式：根据id 删除用户
    @DeleteMapping("/deleteUser")
    public int deleteUser(Integer id){
        return userService.deleteUser(id);
    }

    //get方式：根据name模糊查询用户信息
    @GetMapping("/getUser")
    public List<User> getUser(String name){
        List<User> users = userService.getUser(name);
        return users;
    }

    @GetMapping("/getUserByPage")
    public PageInfo<User> getUserByPage(String name){
        return userService.getUserByPage(name);
    }
}
